package cn.kgc.ssm.service.impl;

import cn.kgc.ssm.commons.ResponseResult;
import cn.kgc.ssm.entity.Member;
import cn.kgc.ssm.entity.Message;
import cn.kgc.ssm.mapper.MessageMapper;
import cn.kgc.ssm.service.MessageService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author 课工场
 * @date 2024/5/17
 * @description
 */
@Service
public class MessageServiceImpl implements MessageService {

    @Resource
    private MessageMapper messageMapper;

    @Override
    public ResponseResult messagePage(Integer page, Integer limit, String memberName) {

        PageHelper.startPage(page,limit);
        List<Message> messages =  messageMapper.searchMessages(memberName);

        PageInfo<Message> messagePageInfo = new PageInfo<>(messages);
        long total = messagePageInfo.getTotal();

        return ResponseResult.success().data(messages).count(total);
    }

    @Override
    public ResponseResult editMessage(Integer id) {

        messageMapper.updateMessage(id);
        return ResponseResult.success().message("回访成功");
    }

    @Override
    public ResponseResult deleteMessage(Integer[] ids) {

        //  判定删除的留言是否已回访  未回访的留言不能删除
       List<Message>  messages =  messageMapper.selectMessagesList(ids);
       if (!ObjectUtils.isEmpty(messages)){
           return  ResponseResult.fail().message("删除的数据包含未回访信息");
       }

        messageMapper.deleteMessages(ids);
        return ResponseResult.success().message("删除成功");
    }

    @Override
    public ResponseResult addMessage(Message message, HttpServletRequest request) {

        Member member = (Member) request.getSession().getAttribute("member");
        String memberName = member.getMemberName();
        String tel = member.getTel();

        message.setTel(tel);
        message.setMemberName(memberName);

        messageMapper.insertMessage(message);

        return ResponseResult.success().message("留言成功");
    }
}
